package leetcode.剑指offer.后40;

import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/8/2 13:56
 * @description :
 */
public class 剑指_67_把字符串转换成整数 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.strToInt("-42"));

    }

    class Solution {
        public int strToInt(String str) {
            str = str.trim();
            if (str == null || str.length() == 0) return 0;
            StringBuilder builder = new StringBuilder();
            int i = 0;
            if (str.charAt(i) == '+' || str.charAt(i) == '-') {
                builder.append(str.charAt(i));
                i++;
            }
            int countNum = 0;
            int left = 12;
            for (; i < Math.min(str.length(), left); i++) {
                char ch = str.charAt(i);
                if (countNum == 0 && ch == '0') {
                    left++;
                    continue;
                }
                if (ch >= '0' && ch <= '9') {
                    builder.append(ch);
                    countNum++;
                } else {
                    if (countNum == 0) return 0;        
                    break;
                }
            }
            System.out.println(builder);
            if (builder.length() == 0) return 0;
            if (builder.length() == 1 && (builder.charAt(0) == '+' || builder.charAt(0) == '-')) return 0;
            long l = Long.parseLong(builder.toString());
            if (l < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            if (l > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            else return (int) l;
        }
    }
}
